package com.mrs.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mrs.common.ResponseResult;
import com.mrs.common.constants.SystemConstants;
import com.mrs.common.vo.CategoryVo;
import com.mrs.entity.Article;
import com.mrs.entity.Category;
import com.mrs.mapper.CategoryMapper;
import com.mrs.service.ArticleService;
import com.mrs.service.CategoryService;
import com.mrs.utils.BeanCopyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 分类表(Category)表服务实现类
 *
 * @author makejava
 * @since 2022-08-06 12:57:31
 */
@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Autowired
    private ArticleService articleService;

    /**
     * @description: 查询分类列表
     * @return: com.mrs.common.ResponseResult
     * @author: MR.孙
     * @date: 2022/8/6 18:17
    */
    @Override
    public ResponseResult getCategoryList() {
        //查询文章表中状态为发布状态的文章
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(Article::getStatus, SystemConstants.ARTICLE_STATUS_NORMAL);
        List<Article> articleList = articleService.list(queryWrapper);

        //获取文章的分类id,并去重
        Set<Long> categoryIds = articleList.stream()
                .map(article -> article.getCategoryId())
                .collect(Collectors.toSet());


        //查询查询分类表 并且状态是正常状态
        List<Category> categoryList = listByIds(categoryIds);
        categoryList=categoryList.stream()
                .filter(category -> SystemConstants.STATUS_NORMAL.equals(category.getStatus()))
                .collect(Collectors.toList());

        //封装VO
        List<CategoryVo> categoryVos = BeanCopyUtils.copyBeanList(categoryList, CategoryVo.class);

        //返回结果
        return ResponseResult.okResult(categoryVos);
    }

    /**
     * @description:  查询所有分类接口
     * @return: com.mrs.common.ResponseResult
     * @author: MR.孙
     * @date: 2022/9/11 22:33
    */
    @Override
    public ResponseResult<List<CategoryVo>> listAllCategory() {
        //查询所有的分类

        //1. 查询条件： 状态为0为正常状态
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Category::getStatus,SystemConstants.STATUS_NORMAL);

        //查询
        List<Category> categoryList = list(queryWrapper);
        List<CategoryVo> categoryVos = BeanCopyUtils.copyBeanList(categoryList, CategoryVo.class);
        //封装数据并返回
        return ResponseResult.okResult(categoryVos);
    }


}
